from common.models.knowledge import Knowledge
from common.models.knowledge_memu import KnowledgeMemu
from flask import Blueprint, request, make_response, redirect
import json, requests
from application import app, db
import datetime

knowledge_page = Blueprint("knowledge_page", __name__)


@knowledge_page.route("/postcontent", methods=['GET', 'POST'])
def postcontent():
    content = request.json.get('content')
    title = request.json.get('title')
    pid = request.json.get('pid')

    sknow = Knowledge.query.filter_by(title=title).first()

    if sknow:
        return json.dumps("请勿重复提交", ensure_ascii=False)

    else:
        knowledge = Knowledge()
        knowledge.content = content
        knowledge.title = title
        db.session.add(knowledge)
        db.session.commit()
        id = knowledge.id

        memu = KnowledgeMemu()
        memu.kid = id
        memu.pid = pid
        memu.name = title
        db.session.add(memu)
        db.session.commit()

        return json.dumps("教程新建成功", ensure_ascii=False)


@knowledge_page.route("/updatecontent", methods=['GET', 'POST'])
def updatecontent():
    id=request.json.get('id')
    mid=request.json.get('mid')
    type = request.json.get('pid')
    content = request.json.get('content')
    title = request.json.get('title')
    knowledge=Knowledge.query.filter_by(id=id).first()
    knowledge.content = content
    knowledge.title = title
    db.session.commit()

    memu = KnowledgeMemu.query.filter_by(id=mid).first()
    memu.pid=type
    db.session.commit()


    return json.dumps("教程更新成功", ensure_ascii=False)


@knowledge_page.route("/getindexcontent", methods=['GET', 'POST'])
def getindexcontent():
    knowledge = Knowledge.query.filter_by(id=1).first()
    content = knowledge.content
    title = knowledge.title
    return json.dumps({"content": content, "title": title}, ensure_ascii=False)


@knowledge_page.route("/getcontent", methods=['GET', 'POST'])
def getcontent():
    kid = request.json.get('kid')
    knowledge = Knowledge.query.filter_by(id=kid).first()
    content = knowledge.content
    title = knowledge.title

    memu = KnowledgeMemu.query.filter_by(kid=knowledge.id).first()
    type=memu.pid

    return json.dumps({"content": content, "title": title,"type":type}, ensure_ascii=False)


@knowledge_page.route("/getmemu", methods=['GET', 'POST'])
def getmemu():
    memu = KnowledgeMemu.query.all()
    rts = []
    for item in memu:
        temp = dict(id=item.id, label=item.name, pid=item.pid, kid=item.kid)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)



@knowledge_page.route("/gettype", methods=['GET', 'POST'])
def gettype():
    memu = KnowledgeMemu.query.filter_by(pid=0).all()
    rts = []
    for item in memu:
        temp = dict(id=item.id, label=item.name, pid=item.pid, kid=item.kid)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)
